$(document).ready(function(){
	// tagging system.
	$("#tags").tagedit({
		allowEdit: false,
		autocompleteOptions: {
			minLength: 2,
			source: function (request, response) {
				$.getJSON(getURL("/tag/search?term=" + request.term), function(data) {
					var list = [];
					$.each(data, function(i, v) {
						if (! v.name) {
							return;
						}
						var item = {
							label: v.name + " - " + v.type[0].name,
							value: v.name,
							id: v.guid
						};
						list.push(item);
					});
					response(list);
				});
			},
			select: function (e, ui) {
				$(this).val(ui.item.value).trigger('transformToTag', [ui.item.id]);
				return false;
			}
		}
	});
	
	// add tooltip for the tags field.
	$(".tagedit-list").attr("rel", "tooltip")
					  .attr("title", "This field is required. You'll have tag suggestions based upon your typing. Note that custom tags are not allowed. Also, you should seperate tags with comma (,).")
					  .attr("data-placement", "right");
	
	// set the tab index for the tags field.
	$("#tagedit-input").attr("tabindex", 2);
	$("input[name='requestItem.title']").blur(function() {
		console.log($("#tagedit-input"));
		$(".tagedit-list").trigger("click");
	});
	
	// configure the participants slider.
	$(function() {
		$("#participantsSlider").slider({
			range: true,
			min: 1,
			max: 50,
			values: [ $("#txt_minNumberOfParticipants").text(), $("#txt_maxNumberOfParticipants").text() ],
			slide: function( event, ui ) {
				$( "#numberOfParticipants" ).text( ui.values[ 0 ] + " - " + ui.values[ 1 ] );
				$("#txt_minNumberOfParticipants").val(ui.values[0]);
				$("#txt_maxNumberOfParticipants").val(ui.values[1]);
			}
			});
			$( "#numberOfParticipants" ).text($( "#participantsSlider" ).slider( "values", 0 ) +
				" - " + $( "#participantsSlider" ).slider( "values", 1 ) );
			$("#txt_minNumberOfParticipants").val($( "#participantsSlider" ).slider( "values", 0 ));
			$("#txt_maxNumberOfParticipants").val($( "#participantsSlider" ).slider( "values", 1 ));
	});
	
	// reoccurrence settings creation.
	$(".repeating").live("change", function() {
		// cache the select element reference.
		var $this = $("#select_repeats");
		
		$(".related_repeats").addClass("hidden");
		
		// daily.
		if ("daily" == $this.val()) { 
			$(".related_repeatsDaily").removeClass("hidden");
		}
		
		// weekly.
		else if ("weekly" == $this.val()) { 
			$(".related_repeatsWeekly").removeClass("hidden");
		}
		
		// update the summary text.
		$("#summary").text(getRepeatingSummaryText($this.val()));
	}).trigger("change");
	
	// virtualization option.
	$("#ddlVirtualization").live("change", function() {
		var value = $(this).val();
		
		if (0 == value) {
			$(".location").removeClass("hidden");
			
			if (! map) {
				initialize();
			}
		} else {
			$(".location").addClass("hidden");
		}
	});
	
	// time specification option.
	$("#ddlTimeDependant").live("change", function() {
		var value = $(this).val();
		
		if (1 == value) {
			$(".timeSpec.showFirst").removeClass("hidden");
		} else {
			$(".timeSpec.showFirst").addClass("hidden");
		}
	});
	
	// initialize tooltips.
	$("a[rel=tooltip],span[rel=tooltip],input[rel=tooltip],select[rel=tooltip],.tagedit-list").tooltip();
	
	// checkbox hack.
	$(".checkboxHack").live("change", function() {
		var $cb = $(this);
		
		// get the name.
		var name = $cb.attr("name");
		
		// if checked;
		if ($cb.is(":checked")) {
			// remove the hack.
			$("input[type='hidden'][name='" + name + "']").remove();
		} else {
			// add the hack.
			$("<input>").attr("type", "hidden").attr("name", name).attr("value", "0").appendTo($("span.checkboxHack"));
		}
	});
	
	// set the datetime pickers.
	$(".date_pick").datetimepicker({
		showSecond: false,
		stepMinute: 15,
		dateFormat: "yy-mm-dd"
	});
	
	// make sure that valid until is greater than the start time.
	// @todo
});

function stringToDate(string) {
	var matches;
	if (matches = string.match(/^(\d{4,4})-(\d{2,2})-(\d{2,2})$/)) {
		return new Date(matches[1], matches[2] - 1, matches[3]);
	} else {
		return null;
	};
}

function dateToString(date) {
	var month = (date.getMonth() + 1).toString();
	var dom = date.getDate().toString();
	if (month.length == 1) month = "0" + month;
	if (dom.length == 1) dom = "0" + dom;
	return date.getFullYear() + "-" + month + "-" + dom;
}

function getRepeatingSummaryText(repeatPeriod) {
	// initialize the summary text.
	var summary = "Once";
	
	// initialize repeat related variables.
	var repeatEveryNDay = $("#select_repeatEveryNDay").val();
	var repeatEveryNWeek = $("#select_repeatEveryNWeek").val();
	var ends = $("input[name='reoccurrenceData.ends']:checked").val();
	var occurrences = parseInt($("#repeat_occurrences").val());
	var endsAt = stringToDate($("#repeat_endsAt").val());

	// daily.
	if ("daily" == repeatPeriod) {
		summary = "Daily";
		
		if (1 < repeatEveryNDay && repeatEveryNDay <= 31) {
			summary = "Every " + repeatEveryNDay + " days";
		}
		
		if ("occurrenceCount" == ends && 1 < occurrences) {
			summary += ", " + occurrences + " times";
		}
		
		else if ("occurrenceCount" == ends && 1 == occurrences) {
			summary = "Once";
		}
		
		else if ("on" == ends && endsAt) {
			summary += ", until " + dateToString(endsAt);
		}
	}
	
	// weekly.
	if ("weekly" == repeatPeriod) {
		summary = "Weekly";
		
		if (1 < repeatEveryNWeek && repeatEveryNWeek <= 52) {
			summary = "Every " + repeatEveryNWeek + " weeks";
		}
		
		// check selected days.
		var onMon = $("input[name='reoccurrenceData.mon']").is(":checked");
		var onTue = $("input[name='reoccurrenceData.tue']").is(":checked");
		var onWed = $("input[name='reoccurrenceData.wed']").is(":checked");
		var onThu = $("input[name='reoccurrenceData.thu']").is(":checked");
		var onFri = $("input[name='reoccurrenceData.fri']").is(":checked");
		var onSat = $("input[name='reoccurrenceData.sat']").is(":checked");
		var onSun = $("input[name='reoccurrenceData.sun']").is(":checked");
		
		if (onMon || onTue || onWed || onThu || onFri || onSat || onSun) {
			summary += " on ";
		}
		var addComma = false;
		if (onMon) {
			summary += "Monday";
			addComma = true;
		}
		if (onTue) {
			if (addComma) summary += ", ";
			summary += "Tuesday";
			addComma = true;
		}
		if (onWed) {
			if (addComma) summary += ", ";
			summary += "Wednesday";
			addComma = true;
		}
		if (onThu) {
			if (addComma) summary += ", ";
			summary += "Thursday";
			addComma = true;
		}
		if (onFri) {
			if (addComma) summary += ", ";
			summary += "Friday";
			addComma = true;
		}
		if (onSat) {
			if (addComma) summary += ", ";
			summary += "Saturday";
			addComma = true;
		}
		if (onSun) {
			if (addComma) summary += ", ";
			summary += "Sunday";
		}
		
		if ("occurrenceCount" == ends && 1 < occurrences) {
			summary += ", " + occurrences + " times";
		}
		
		else if ("occurrenceCount" == ends && 1 == occurrences) {
			summary = "Once";
		}
		
		else if ("on" == ends && endsAt) {
			summary += ", until " + dateToString(endsAt);
		}
	}
	
	return summary;
}